<?php 
  
if(filter_input(INPUT_POST, 'req') == "fileando")
{   
    ini_set('max_execution_time', 0);     
    $database_ = json_decode(filter_input(INPUT_POST, 'database_')); 
    $bat_ = fopen("cmd_.bat", "w+") or die(json_encode("No .bat")); 
    fwrite($bat_, "@ECHO OFF\nexit|sqlplus -s ".$database_[0]."/".$database_[1]."@".$database_[2]." @run.sql");//C:\xampp\htdocs\InstaladorBD\
    //Archive
    $archive_= json_decode(filter_input(INPUT_POST, 'archive_'));
    $sBuild = "";  
    $sInit = "";
    $sRun = "shutdown abort;\nstartup nomount pfile=";
    $sTempFile = "";
    $Run_ = fopen("run.sql", "w+") or die("no abrió run.sql"); 
    $bandera = false;
    //Build
    $bd_name_ = filter_input(INPUT_POST, 'bd_name_');
    $system_ = json_decode(filter_input(INPUT_POST, 'system_'));
    $sysaux_ = json_decode(filter_input(INPUT_POST, 'sysaux_'));
    $undo_ = json_decode(filter_input(INPUT_POST, 'undo_'));
    $temp_ = json_decode(filter_input(INPUT_POST, 'temp_'));   
    $logs_ = json_decode(filter_input(INPUT_POST, 'logs_'));    
    $build_path_ = filter_input(INPUT_POST, 'build_path_');    
    $paths = Array($sysaux_[3], $system_[3],$undo_[3]);    
    for($i = 0; $i < sizeof($temp_); $i++){
        array_push($paths, ($temp_[$i][1])); }  
     $dirname = dirname($build_path_."\build.sql");
    if (!is_dir($dirname))
    {
        mkdir($dirname, 0755, true);
    } 
    for($i = 0; $i < sizeof($paths); $i++)
    {
        $dirname1 = NULL;
        $dirname1 = dirname($paths[$i]."\h".$i.".txt");
        if (!is_dir($dirname1))
        {
            mkdir($dirname1, 0755, true);
        } 
    }
    $build_ = fopen($build_path_."\build.sql", "w+") or die(json_encode($paths)); //$build_path_ 
    $sBuild.= "create database ".$bd_name_."\nUSER SYS IDENTIFIED BY root\nUSER SYSTEM IDENTIFIED BY root\nlogfile "; 
    for($i = 0; $i< sizeof($logs_); $i++) 
    {  
          $sBuild.="group ".$logs_[$i][0]."(";
            for($j = 0; $j < sizeof($logs_[$i][3]); $j++)
            {
                if($logs_[$i][3][$j] != NULL && $logs_[$i][3][$j] != "") 
                {   
                    $dirname2 = NULL;
                    $dirname2 = dirname($logs_[$i][3][$j]."\h".$j.".txt");
                    if (!is_dir($dirname2))
                        mkdir($dirname2, 0755, true);
                    if($j == sizeof($logs_[$i][3])-1 || ($logs_[$i][3][$j+1] == NULL || $logs_[$i][3][$j+1] == ""))
                        $sBuild.="'".$logs_[$i][3][$j]."\LOG".$logs_[$i][0].$j.".log'"; 
                    else 
                        $sBuild.="'".$logs_[$i][3][$j]."\LOG".$logs_[$i][0].$j.".log',";
                }
            }
        if($i == sizeof($logs_)-1)
        {
            $sBuild.=") size ".$logs_[$i][1].$logs_[$i][2]."\n";
        }
        else
        { 
            $sBuild.=") size ".$logs_[$i][1].$logs_[$i][2].",\n";
        }
    } 
    $sBuild.="MAXLOGFILES 3\nMAXLOGMEMBERS 3\nMAXLOGHISTORY 1\nMAXDATAFILES 100\nMAXINSTANCES 1\ncharacter set WE8ISO8859P1\nnational character set utf8\n";
    if(is_numeric($system_[1]) && is_numeric($system_[2]))
        $sBuild.="datafile "."'".$system_[3]."\system.dbf' size ".$system_[0].$system_[4]." autoextend on next ".$system_[1].$system_[5]." maxsize ".$system_[2].$system_[6]."\n";
    elseif(is_numeric($system_[1])) 
        $sBuild.="datafile "."'".$system_[3]."\system.dbf' size ".$system_[0].$system_[4]." autoextend on next ".$system_[1].$system_[5]." maxsize ".$system_[2]."\n"; 
    else
        $sBuild.="datafile "."'".$system_[3]."\system.dbf' size ".$system_[0].$system_[4]."\n"; 
    if(is_numeric($sysaux_[1]) && is_numeric($sysaux_[2]))
        $sBuild.= "sysaux datafile '".$sysaux_[3]."\sysaux.dbf' size ".$sysaux_[0].$sysaux_[4]." autoextend on next ".$sysaux_[1].$sysaux_[5]." maxsize ".$sysaux_[2].$sysaux_[6]."\n";
    elseif(is_numeric($sysaux_[1])) 
        $sBuild.= "sysaux datafile '".$sysaux_[3]."\sysaux.dbf' size ".$sysaux_[0].$sysaux_[4]." autoextend on next ".$sysaux_[1].$sysaux_[5]." maxsize ".$sysaux_[2]."\n";
    else
        $sBuild.= "sysaux datafile '".$sysaux_[3]."\sysaux.dbf' size ".$sysaux_[0].$sysaux_[4]."\n";
    $sBuild.= "undo tablespace undotbs1 datafile '".$undo_[3]."\undotbs1.dbf' size ".$undo_[0].$undo_[4]."\n"; 
    $sBuild.= "default temporary tablespace temp tempfile '".$temp_[0][1]."\\temp0.dbf' size ".$temp_[0][0].$temp_[0][2].";";
    for($i = 1; $i < sizeof($temp_); $i++)
       $sTempFile.= "CREATE TEMPORARY TABLESPACE temp".$i." TEMPFILE '".$temp_[$i][1]."\\temp".$i.".dbf' size ".$temp_[$i][0].$temp_[$i][2].";\n";
    fwrite($build_, $sBuild);
    //build
//-------------------------------------------------------------------------------------------------------------------------------------------------------//
    //init   
    $cache_ = filter_input(INPUT_POST,'cache_');
    $large_ = filter_input(INPUT_POST,'large_');
    $java_ = filter_input(INPUT_POST,'java_');
    $shared_ = filter_input(INPUT_POST,'shared_');  
    $block_size_ = filter_input(INPUT_POST,'block_size_'); 
    $control_file1 = filter_input(INPUT_POST, 'control_file1');
    $control_file2 = filter_input(INPUT_POST, 'control_file2');
    $Header = '$Header';
    $init_path_= filter_input(INPUT_POST, 'init_path_'); 
    $dirname0 = dirname($init_path_."\init.ora");
    if (!is_dir($dirname0))
    {
        mkdir($dirname0, 0755, true);
    }
    $init = fopen($init_path_."\init.ora", "w+") or die("Unable to open file!");   
    if($archive_[0])
        $sRun.=$init_path_."\init.ora;\n@".$build_path_."\build.sql\n".$sTempFile."shutdown immediate;\nstartup mount pfile=".$init_path_."\init.ora;\n".
"alter database archivelog;\nexit;";   
    else
        $sRun.=$init_path_."\init.ora;\n@".$build_path_."\build.sql\n".$sTempFile."exit;";   
    
    $shh= ""; 
    $shh.="startup;\ncreate table xxxx(a int);\ncommit;\nexit;";
    fwrite($Run_, $sRun);
    $sInit.= "#".$Header.": init.ora 25-jul-01.18:03:38 rajayar Exp $
# Copyright (c) 1991, 2001, Oracle Corporation.  All rights reserved.
##############################################################################
# Example INIT.ORA file
#
# This file is provided by Oracle Corporation to help you customize
# your RDBMS installation for your site.  Important system parameters
# are discussed, and example settings given.
#
# Some parameter settings are generic to any size installation.
# For parameters that require different values in different size
# installations, three scenarios have been provided: SMALL, MEDIUM
# and LARGE.  Any parameter that needs to be tuned according to
# installation size will have three settings, each one commented
# according to installation size.
#
# Use the following table to approximate the SGA size needed for the
# three scenarious provided in this file:
#
#                     -------Installation/Database Size------
#                      SMALL           MEDIUM           LARGE
#  Block         2K    4500K            6800K           17000K
#  Size          4K    5500K            8800K           21000K
###############################################################################
#
#	Modificada para fines didácticos por Juan J. Salazar & Javier Buzano
#	juan1992.cucus@gmail.com, jabuma13@gmail.com
#
###############################################################################\n
db_name = ".$bd_name_."\n
#//////////////////  MODIFIQUE EL NOMBRE IGUAL AL INIT QUE CREE\n
db_files = 1024 #INITIAL
#db_files=80    #SMALL 
#DB_files=400   #MEDIUM
#db_files=1000  #LARGE

#Debe tener controlfiles en discos duros apartes\n
control_files =('".$control_file1."\controlfile01','".$control_file2."\controlfile02')\n
db_file_multiblock_read_count =  8   #INITIAL
#db_file_multiblock_read_count = 8   #SMALL 
#db_file_multiblock_read_count = 16  #MEDIUM
#db_file_multiblock_read_count = 32  #LARGE

open_cursors=300

##################################################################################
# 
# Cuando el parámetro SGA_TARGET tiene valor entonces la base de datos
# gestina automáticamente el tamaño de los parametros:
#    - DB_CACHE_SIZE
#    - SHARED_POOL_SIZE
#    - LARGE_POOL_SIZE
#    - JAVA_POOL_SIZE
# Si se especifican alguno de los parametros entonces estos serán tomados
# como valores mínimos. El parametro SGA_MAX_SIZE puede ser cambiado 
# incluso con la instancia activa. Se debe cumplir que SGA_MAX_SIZE > SGA_TARGET
#
#SGA_MAX_SIZE = 3G  #TAMAÑO FIJO QUE NO VA A A CAMBIAR SI LO ACTIVO  // CUOTA SUPERIOR\n
SGA_TARGET   = 2G   # target tiene 2 GB    //CUOTA INTERMEDIA

# CUOTA INFERIOR DETERMINADA POR LOS VALORES DE ABAJO

large_pool_size  = ".$large_."  
db_cache_size    = ".$cache_."
java_pool_size   = ".$java_."
shared_pool_size = ".$shared_."

db_block_size = ".$block_size_." 
log_checkpoint_interval = 10000    #Número de procesos antes de cambiar log

processes  = 59                   # INITIAL
#processes = 50  			      #SMALL
#processes = 100 				  #MEDIUM
#processes = 200  				  #LARGE

log_buffer =  8192   			 # INITIAL
#log_buffer =  8192  			 #SMALL
#log_buffer = 32768  			 #MEDIUM
#log_buffer = 163840 			 #LARGE

# audit_trail = true            # if you want auditing
# timed_statistics = true       # if you want timed statistics
max_dump_file_size = 10240      # limit trace file size to 10 K each

# CREA UNA COPIA DE LOS REDO PARA DARLE SEGURIDAD A LA BASE DE DATOS


# Uncommenting the line below will cause automatic archiving if archiving has
# been enabled using ALTER DATABASE ARCHIVELOG.

#  DESCOMENTAR LAS SIGUEINTES 3 LINEAS
 log_archive_dest =".$archive_[1]." # DONDE SE VAN A GUARDAR
 log_archive_format =".$archive_[2]." # FORMATO EN EL QUE SE VA A GUARDAR

global_names = TRUE

################################################################################## \n";
    fwrite($init, $sInit);
    //fin del init
    $bandera = (fclose($build_) && fclose($init) && fclose($Run_)); 
    if($bandera)
    {   
        
        //exec("C:/xampp/htdocs/InstaladorBD/prueba.bat");
        exec("cmd_.bat");
        print(json_encode($logs_));
    }
    else 
        print(json_encode("Mamó")); 
} 
else
    print(json_encode ("Bad Request")); 

/*shutdown abort; 
startup nomount pfile=C:\BD1\HD1\init.ora;  
@buildpath 
@tempfiles
@catalogos
 * exit;"
 */